package cn.person.weichangjie.toolset;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 格式化时间：多久之前
 * 
 * @author weichangjie
 *
 */
public class TimeFormatUtil {

	public static String getInterval(Date createAt) {
		// 定义最终返回的结果字符串。
		String interval = null;
		long millisecond = new Date().getTime() - createAt.getTime();
		long second = millisecond / 1000;
		if (second <= 0) {
			second = 0;
		}
		if (second < 60) {
			interval = "刚刚";
		} else if (second >= 60 && second < 60 * 60) {// 大于1分钟 小于1小时
			long minute = second / 60;
			interval = minute + "分钟前";
		} else if (second >= 60 * 60 && second < 60 * 60 * 24) {// 大于1小时 小于24小时
			long hour = (second / 60) / 60;
			if (hour <= 3) {
				interval = hour + "小时前";
			} else {
				interval = "今天 " + getFormatTime(createAt, "HH:mm");
			}
		} else if (second >= 60 * 60 * 24 && second <= 60 * 60 * 24 * 2) {// 大于1D
																			// 小于2D
			interval = "昨天 " + getFormatTime(createAt, "HH:mm");
		} else if (second >= 60 * 60 * 24 * 2 && second <= 60 * 60 * 24 * 3) {// 大于1D
																				// 小于2D
			interval = "前天 " + getFormatTime(createAt, "HH:mm");
		} else if (second >= 60 * 60 * 24 * 3 && second <= 60 * 60 * 24 * 365) {// 大于7天小于365天
			interval = getFormatTime(createAt, "M月d日 HH:mm");
		} else if (second >= 60 * 60 * 24 * 365) { // 大于365天
			interval = getFormatTime(createAt, "yyyy年M月d日 HH:mm");
		} else {
			interval = "0";
		}
		return interval;
	}

	public static String getFormatTime(Date date, String Sdf) {
		return (new SimpleDateFormat(Sdf)).format(date);
	}

	public static Date getParserTime(String date, String Sdf) {
		try {
			return (new SimpleDateFormat(Sdf)).parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

}
